/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UI;

/**
 *
 * @author marco
 */
import Logica.Accion;
import Persistencia.*;
import java.util.Calendar;
import java.util.Date;
import javax.swing.*;
import Excepciones.*;
import Logica.Usuario;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
public class ICargaAccion extends javax.swing.JFrame {
    
    ADOAccion adoaccion = new ADOAccion();
    /**
     * Creates new form ICargaAccion
     */
    public ICargaAccion() {
        initComponents();
        this.darFormatoATexto();
        this.cargarUsuarios();
       
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblNombre = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        lblDescripcion = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDescripcion = new javax.swing.JTextArea();
        lblUsuario = new javax.swing.JLabel();
        cmbUsuario = new javax.swing.JComboBox();
        btnGuardar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        lblVencimiento = new javax.swing.JLabel();
        txtFechaVencimiento = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lblNombre.setText("Nombre:");

        lblDescripcion.setText("Descripcion: ");

        txtDescripcion.setColumns(20);
        txtDescripcion.setRows(5);
        jScrollPane1.setViewportView(txtDescripcion);

        lblUsuario.setText("Usuario");

        cmbUsuario.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        lblVencimiento.setText("Vence: ");

        txtFechaVencimiento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));
        txtFechaVencimiento.setToolTipText("Formato: dd/mm/yyyy");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(74, 74, 74)
                .addComponent(btnGuardar)
                .addGap(29, 29, 29)
                .addComponent(btnCancelar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(lblDescripcion)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lblNombre))
                            .addGap(50, 50, 50)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lblUsuario)
                                .addComponent(cmbUsuario, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblVencimiento)
                        .addGap(1, 1, 1)
                        .addComponent(txtFechaVencimiento, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(0, 10, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNombre)
                    .addComponent(lblUsuario))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblDescripcion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblVencimiento)
                    .addComponent(txtFechaVencimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 68, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGuardar)
                    .addComponent(btnCancelar))
                .addGap(32, 32, 32))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
      this.dispose();
       
        
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        Accion nuevaAccion = new Accion();
        try
        {    
            if(this.txtFechaVencimiento.getText().trim().length()<10){
               throw   new FechaIncorrectaException();
            }
            this.validarDiasMesFecha(this.txtFechaVencimiento.getText());
            nuevaAccion.setFechaVencimiento(this.txtFechaVencimiento.getText());
            if(nuevaAccion.getFechaVencimiento().compareTo(this.obtenerFechaActual())<1){
               throw  new FechaInferiorException();
            }
             nuevaAccion.setNombre(this.txtNombre.getText());
             nuevaAccion.setDescripcion(this.txtDescripcion.getText());
            //hardcodeado hasta que este resuelto lo de usuario
             nuevaAccion.setFechaCreacion(this.obtenerFechaActualString());
             nuevaAccion.setUsuario(this.cmbUsuario.getSelectedItem().toString().toLowerCase());
             adoaccion.insertarAccion(nuevaAccion);
             JOptionPane.showMessageDialog(null,"La Acción se cargo existosamente","Exíito",JOptionPane.INFORMATION_MESSAGE);
            this.txtNombre.setText("");
             this.txtDescripcion.setText("");
             this.txtFechaVencimiento.setText("");
        
        
        }
        catch(FechaIncorrectaException fine){
          JOptionPane.showMessageDialog(null, fine.toString(),"Error", JOptionPane.ERROR_MESSAGE );   
        }
        catch (FechaInferiorException fie){
           JOptionPane.showMessageDialog(null, fie.toString(),"Error", JOptionPane.ERROR_MESSAGE );     
     
        }
        /*
        try{
          Accion nuevaAccion = new Accion();
         
        
        }
        catch (Exception e){
            JOptionPane.showMessageDialog(null, "Error no se inserto");
            e.printStackTrace();
        
        }
        * */
    }//GEN-LAST:event_btnGuardarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ICargaAccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ICargaAccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ICargaAccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ICargaAccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ICargaAccion().setVisible(true);
            }
        });
    }
    
    
    public void darFormatoATexto(){
    
    try{
     txtFechaVencimiento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
     
    }
    catch (Exception e){
    e.printStackTrace();}
    }
    public Date obtenerFechaActual(){
     java.util.Date fecha = new Date();
     return fecha;
    }
    public String obtenerFechaActualString(){
       java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("dd-MM-yyyy");
       String fecha = sdf.format(this.obtenerFechaActual());
       return fecha;
    }
  public void validarDiasMesFecha(String fecha) throws FechaIncorrectaException{
      
      String decenaDia = String.valueOf(fecha.charAt(0)); 
      String unidadDia = String.valueOf(fecha.charAt(1));
      String decenaMes = String.valueOf(fecha.charAt(3));
      String unidadMes = String.valueOf(fecha.charAt(4));
      String [] splitFecha = fecha.split("-"); // tomo el es, para ver si es febrero y validar diferente
      
      if(Integer.valueOf(splitFecha[1])==2){
       if((Integer.parseInt(decenaDia)>2) || (Integer.parseInt(unidadDia)>8  && Integer.parseInt(decenaDia) <= 2 ) )

           throw new FechaIncorrectaException();
      }
      else{
        if(Integer.parseInt(decenaDia)>3 || Integer.parseInt(decenaMes)>1 ||
                (Integer.parseInt(decenaDia)==3 && Integer.parseInt(unidadDia)>1) || (Integer.parseInt(decenaMes)==1 && Integer.parseInt(unidadMes)>2))
            throw new FechaIncorrectaException();
      
      }
      
      
     }
  /*Carga el combobox con los usuarios disponibles*/
  public void cargarUsuarios(){
      ADOUsuario adusr = new ADOUsuario();
      this.cmbUsuario.removeAllItems();
      Iterator iter = adusr.traerSoloUsuarios().iterator();
      while (iter.hasNext()){
           Usuario usr = (Usuario)iter.next();
        this.cmbUsuario.addItem(usr.getNombreUsuario());
      
      }
  }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cmbUsuario;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblDescripcion;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JLabel lblVencimiento;
    private javax.swing.JTextArea txtDescripcion;
    private javax.swing.JFormattedTextField txtFechaVencimiento;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}


